package com.lxl.xm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxl.xm.common.ErrorCode;
import com.lxl.xm.exception.BusinessException;
import com.lxl.xm.mapper.StudentBranchTaskMapper;
import com.lxl.xm.mapper.StudentUserMapper;
import com.lxl.xm.mapper.TaskMapper;
import com.lxl.xm.model.dto.student_branch.StudentCompleteBranchRequest;
import com.lxl.xm.model.dto.student_branch.StudentJoinBranchRequest;
import com.lxl.xm.model.dto.task_branch.TaskBranchAddRequest;
import com.lxl.xm.model.entity.StudentBranchTask;
import com.lxl.xm.model.entity.StudentUser;
import com.lxl.xm.model.entity.Task;
import com.lxl.xm.model.entity.TaskBranch;
import com.lxl.xm.service.TaskBranchService;
import com.lxl.xm.mapper.TaskBranchMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
* @author 86135
* @description 针对表【task_branch(分支任务表)】的数据库操作Service实现
* @createDate 2024-03-19 22:05:57
*/
@Service
public class TaskBranchServiceImpl extends ServiceImpl<TaskBranchMapper, TaskBranch>
    implements TaskBranchService{

    @Resource
    StudentBranchTaskMapper studentBranchTaskMapper;

    @Resource
    StudentUserMapper studentUserMapper;

    @Resource
    TaskMapper taskMapper;

    @Resource
    TaskBranchMapper taskBranchMapper;

    /**
     * 学生参加支线任务
     * @param studentJoinBranchRequest
     * @return
     */
    @Override
    public Boolean studentJoinTaskBranch(StudentJoinBranchRequest studentJoinBranchRequest) {
        Long studentId = studentJoinBranchRequest.getStudentId();
        Long taskId = studentJoinBranchRequest.getTaskId();
        Long taskSubId = studentJoinBranchRequest.getTaskSubId();
        if (studentId < 0 || taskId < 0 || taskSubId < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数错误");
        }
        StudentBranchTask studentBranchTask = new StudentBranchTask();
        //学生id
        studentBranchTask.setStudentId(studentId);
        //主线任务id
        studentBranchTask.setTaskId(taskId);
        //任务子id
        studentBranchTask.setBranchSubTaskId(taskSubId);
        //学生信息表存放参加活动的信息
        studentUserMapper.updateJoinTask(studentId,taskId,taskSubId);
        return studentBranchTaskMapper.insert(studentBranchTask) == 1;
    }

    /**
     * 添加支线任务
     * @param taskBranchAddRequest
     * @return
     */
    @Override
    @Transactional
    public Boolean addBranchTask(TaskBranchAddRequest taskBranchAddRequest) {
        //添加
        Long taskId = taskBranchAddRequest.getTaskId();
        //
        TaskBranch taskBranch = new TaskBranch();
        BeanUtils.copyProperties(taskBranchAddRequest,taskBranch);
        //主任务是否存在
        Task task = taskMapper.selectById(taskId);
        if (task == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"主任务不存在");
        }
        //计数器
        Long subTaskCounter = Long.valueOf(task.getSubTaskCounter());
        taskBranch.setTaskSubId(subTaskCounter + 1);
        //任务表的更新，分支任务数加一
        LambdaUpdateWrapper<Task> taskLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        taskLambdaUpdateWrapper.eq(Task::getId,taskId)
                .setSql("sub_task_counter = sub_task_counter + 1");
        int affectRows = taskMapper.update(task, taskLambdaUpdateWrapper);
        //插入支线任务
        int insert = taskBranchMapper.insert(taskBranch);
        return affectRows == 1 && insert == 1;
    }

    /**
     * 学生完成支线任务
     * @param studentCompleteBranchRequest
     */
    @Override
    @Transactional
    public void studentCompleteBranchTask(StudentCompleteBranchRequest studentCompleteBranchRequest) {
        Long studentId = studentCompleteBranchRequest.getStudentId();
        Long taskId = studentCompleteBranchRequest.getTaskId();
        Long taskSubId = studentCompleteBranchRequest.getTaskSubId();
        if (studentId < 0 || taskId < 0 || taskSubId < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数错误");
        }
        //1.学生是否参加了本支线任务
        QueryWrapper<StudentBranchTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id",studentId)
                .eq("task_id",taskId)
                .eq("branch_sub_task_id",taskSubId);
        StudentBranchTask studentBranchTask = studentBranchTaskMapper.selectOne(queryWrapper);
        if (studentBranchTask == null){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"学生未参加该支线任务");
        }
        //2.学生是否已经完成
        if (studentBranchTask.getIsCompleted() == 1){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"学生已完成任务，不允许重复完成");
        }
        //3.学生信息表更新complete_task字段
            // 获取学生当前的 task_complete 值
        StudentUser studentUser = studentUserMapper.selectById(studentId);
        String currentTaskComplete = studentUser.getTaskComplete();
            // 将新完成的支线任务 ID 添加到当前 task_complete 字段值的末尾
        if (currentTaskComplete == null){
            currentTaskComplete = taskId + "|" + taskSubId;
            studentUser.setTaskComplete(currentTaskComplete);
        }else {
            String newTaskComplete = currentTaskComplete + (currentTaskComplete.isEmpty() ? "" : ",") + taskId + "|" + taskSubId;
            studentUser.setTaskComplete(newTaskComplete);
        }
        //4. 加分数
        QueryWrapper<TaskBranch> taskBranchQueryWrapper = new QueryWrapper<>();
        taskBranchQueryWrapper.eq("task_id",taskId)
                        .eq("task_sub_id",taskSubId);
        TaskBranch taskBranch = taskBranchMapper.selectOne(taskBranchQueryWrapper);
        Integer newScore = studentUser.getScore() + taskBranch.getAward();
        studentUser.setScore(newScore);
        studentUserMapper.updateById(studentUser);
        //5.学生分支任务表更新完成字段
        studentBranchTask.setIsCompleted(1);
        studentBranchTask.setCompleteDate(new Date());
        int i = studentBranchTaskMapper.updateById(studentBranchTask);
        if (i == 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"完成失败");
        }
    }
}




